##### ThreadPool * #####
import Queue
import threading

class ThreadManager(threading.Thread):
    def __init__(self, worker, queue):
        """
        worker: a worker function
        """
        threading.Thread.__init__(self)
        self.queue = queue
        self.worker = worker

    def run(self):
        while True:
            para = self.queue.get()
            self.worker(para)
            self.queue.task_done()

class ThreadPool():
    def __init__(self, worker, worker_number, paras):
        """
        worker: a worker function
        paras: a list of [para]s. a worker process one [para] each time
        """

        self.worker_number = worker_number
        self.worker = worker
        self.paras = paras
        self.queue = Queue.Queue()

    def run(self):
        for i in range(self.worker_number):
            t = ThreadManager(self.worker, self.queue)
            t.setDaemon(True)
            t.start()
            
        for para in self.paras:
            self.queue.put(para)
 
        self.queue.join()

##### ThreadPool #####
class Fenci():
    from pymmseg import mmseg
    
    mutex = 0
    initiated = False

    @classmethod
    def initiate(cls):
        Fenci.mmseg.dict_load_defaults()
        cls.mutex = threading.Lock()
        cls.initiated = True

    @classmethod
    def fenci(cls, text):
        """
        input:
            text: a string
        output:
            a keyword list contained in [text]
        """
        cls.mutex.acquire()
        algor = Fenci.mmseg.Algorithm(text)
        cls.mutex.release()
        return [tok.text.decode('utf8') for tok in algor]

def safe_print(s):
    import types
    t = type(s)
    if t == types.ListType:
        for x in s:
            if type(x) == types.UnicodeType:
                print '%s; ' % x.encode('gbk', 'ignore'), 
            else:
                print '%s; ' % x,
    elif t == types.DictionaryType:
        for (key, value) in t.items():
            print key.encode('gbk', 'ignore'), value        
    elif t == types.UnicodeType:
        print s.encode('gbk', 'ignore')
    else:
        try:
            print s
        except Exception, e:
            print 'cannot print. error=%s' % e

    print 

def drop_tag(e, tag):
    """
    input:
        e: HtmlElement
        tag_to_drop: str
    output:
        e
    Desc: 
        a wrap up of the drop_tag method lxml.htmlelement.drop_tag. remove all the tags of [tag] from e
    """
    _tags = e.findall(tag)
    if(len(_tags)):
        for _tag in _tags:
            _tag.drop_tag()
    return e

def HttpResponseRedirectAfter(url, message, s=3000):
    """
    input:
        url|str
        message|str
        s|int
    desc:
        show [message] and redirect to [url] after [s] ms
    """
    from django.http import HttpResponse
    return HttpResponse("""<body onload="javascript:setTimeout(function(){window.location.href='%s'},%d);">%s</body>""" % (url, s, message))

def login_validation(view_func):#decorator method
    def wrapper(*args, **kw):
        request = args[0]
        if not request.session.get('uid'):
            return HttpResponseRedirectAfter('/citylife/login/', 'have to login first')
        return view_func(*args, **kw)
    return wrapper

@login_validation
def authorization(view_func):
    from django.http import HttpResponseRedirect

    def wrapper(*args, **kw):
        request = args[0]
        uid = request.session.get('uid')
        user = User.objects.get(id = uid)
        if(not (user.douban_access_key and user.douban_access_secret)):
            return HttpRequestRedirect('/citylife/register_import')
        return view_func(*args, **kw)
    return wrapper
